﻿namespace OverStore.Scoping
{
    using System;
    using System.Globalization;
    using OverStore.Scoping.Manager;

    /// <summary>
    /// Makes code block atomar. This class cannot be inherited.
    /// </summary>
    /// <remarks>
    ///     <para> Current class is very similar to System.Transactions.TransactionScope and
    /// it is more simple version of such class need to be introduced because TransactionScope
    /// does not supported by .NET Compact Framework.</para>
    ///     <para>
    /// Operation scopes are hierarchical and child scopes automatically propagates and extends to outer scope.
    /// The only important scope is root scope, which disposing or completing causes <see cref="OverStore.Scoping.Manager.OperationScopeManager"/>
    /// to notify its subscribers about scope completing or disposing. All other child scopes completing or disposing does not affect
    /// nothing and does not affect parent scope.
    /// </para>
    /// </remarks>
    public sealed class OperationScope : IDisposable
    {
        private readonly int _ScopeId;
        private readonly bool _NonRoot;
        private static volatile int _ScopeIdCounter = -1;
        private bool _Disposed;
        private bool _Completed;

        /// <summary>
        /// Initializes a new instance of the <see cref="OperationScope"/> class.
        /// </summary>
        internal OperationScope()
        {
            _ScopeIdCounter += 1;
            _ScopeId = _ScopeIdCounter;
        }

        internal OperationScope(bool nonRoot)
        {
            _NonRoot = nonRoot;
        }

        internal int Id
        {
            get
            {
                return _ScopeId;
            }
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            if (_NonRoot)
                return "<Non-root>";
            return String.Format(CultureInfo.InvariantCulture, "Scope #{0}", _ScopeId);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (_NonRoot)
                return;
            if (!_Disposed)
            {
                _Disposed = true;
                if (!_Completed && Failed != null)
                    Failed(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Indicates that all operations within current scope are completed successfully.
        /// </summary>
        /// <exception cref="T:System.ObjectDisposedException">The object is displosed.</exception>
        /// <exception cref="T:System.InvalidOperationException">The method is already called for this instance.</exception>
        public void Complete()
        {
            if (_NonRoot)
                return;
            if (_Disposed)
                throw new ObjectDisposedException(this.ToString());
            if (_Completed)
                throw new InvalidOperationException("Complete method already called on this instance.");
            _Completed = true;
            if (Completed != null)
                Completed(this, EventArgs.Empty);
        }

        /// <summary>
        /// Occurs when current scope is completed.
        /// </summary>
        internal event EventHandler Completed;

        /// <summary>
        /// Occurs when current scope is failed.
        /// </summary>
        internal event EventHandler Failed;
    }
}
